package com.dai.chun.dao.action;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.dai.chun.dao.dao.AdminDao;
import com.dai.chun.dao.impl.AdminDaoImpl;
import com.dai.chun.dao.model.Admin;
import com.dai.chun.util.EncrypterUti;
import com.dai.chun.util.PageSplitUtil;

/**
 * 
 * @author Administrator
 * 
 */
public class AdminAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private AdminDao adminDao;
	private Admin admin;
	private List<Admin> adminList;
	private PageSplitUtil psu;

	// 添加
	public String addAdmin() throws IOException, SQLException {
		// 两次输入的密码是否相等
		if (admin.getAdmin_password().equals(admin.getRe_password())) {
			// 给密码加密
			admin.setAdmin_password(EncrypterUti.encrypt(admin
					.getAdmin_password()));
			adminDao = new AdminDaoImpl();
			adminDao.save(admin);
			return "addAdmin";
		}
		return "fail";

	}

	// 列出所有管理员
	public String listAdmin() throws IOException, SQLException {
		adminDao = new AdminDaoImpl();
		if (psu == null) {
			psu = new PageSplitUtil(1);
		}
		psu.comput();
		psu.computPageCount(adminDao.findAllCount());
		adminList = adminDao.listAdmin(psu);
		return "listAdmin";
	}

	// 删除
	public String delAdmin() throws SQLException {
		adminDao = new AdminDaoImpl();
		HttpSession session = ServletActionContext.getRequest().getSession();
		if (null == session) {
			return "login";
		}
		// 管理员不能删除自己
		if (((Admin) session.getAttribute("admin")).getAdmin_id() != admin
				.getAdmin_id()) {
			adminDao.delAdmin(admin.getAdmin_id());
			return "delAdmin";
		}
		return "fail";
	}

	// 修改
	public String updateAdmin() throws SQLException {
		adminDao = new AdminDaoImpl();
		String oldPassword=admin.getAdmin_password();
		String newPassword=admin.getRe_password();
		admin=adminDao.findAdminById(admin.getAdmin_id());
		// 输入的旧密码是否正确
		if ( EncrypterUti.verify(admin.getAdmin_password(), oldPassword)) {
			admin.setAdmin_password(EncrypterUti.encrypt(newPassword));
			adminDao.updateAdmin(admin);
			return "updateAdmin";
		}
		return "fail";
	}

	public String showUpdateAdmin() throws SQLException {
		adminDao = new AdminDaoImpl();
		return "showUpdateAdmin";
	}

	public List<Admin> getAdminList() {
		return adminList;
	}

	public void setAdminList(List<Admin> adminList) {
		this.adminList = adminList;
	}

	public Admin getAdmin() {
		return admin;
	}

	public void setAdmin(Admin admin) {
		this.admin = admin;
	}

	public PageSplitUtil getPsu() {
		return psu;
	}

	public void setPsu(PageSplitUtil psu) {
		this.psu = psu;
	}

}
